﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using DevExpress.Web.Mvc;
using EnterpriseFund.Common;
using Newtonsoft.Json;
using DevExpress.Web.ASPxGridView;
using System.Web.UI;
using DevExpress.XtraReports.UI;
using DevExpress.XtraPrinting;

namespace EnterpriseFund.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]  
    public class QueryTaxController : AdminBaseController
    {
        private string IsNull(string s1, string s2)
        {
            return string.IsNullOrEmpty(s1) ? s2 : s1;
        }
        public ActionResult ReportViewerPartial()
        {
           // var strWhere = GetWhereString();
            var zsxx = GetVSBZSXX();
            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryTax") as MVCxGridViewState, zsxx);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;

            this.ViewData["rpt"] = report;

            return PartialView("ReportViewerPartial");

        }
        public ActionResult Print()
        {
            GetWhereString();
            // CreatReport(table);
            return View("Print");
        }
        void generator_CustomizeColumnsCollection(object source, ColumnsCreationEventArgs e)
        {

             for (int i = 0; i < e.ColumnsInfo.Count; i++)
            {

                if (e.ColumnsInfo[i].FieldName == "NSRSBH")
                {
                    e.ColumnsInfo[i].ColumnWidth =170 ;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRBM")
                {
                    e.ColumnsInfo[i].ColumnWidth =  80;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRMC")
                {
                    e.ColumnsInfo[i].ColumnWidth =320;

                }
                if (e.ColumnsInfo[i].FieldName == "ZSXM_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "YSKM_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "SE")
                {
                    e.ColumnsInfo[i].ColumnWidth = 120;
                }
                 
                if (e.ColumnsInfo[i].FieldName == "HYDL_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "SKZL_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth =60 ;
                }
                if (e.ColumnsInfo[i].FieldName == "SKSX_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth =100;

                }
                if (e.ColumnsInfo[i].FieldName == "ZSFS_MC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "FDataSource")
                {
                    e.ColumnsInfo[i].ColumnWidth = 60;
                }
                

            }
          
        }
        void generator_CustomizeColumn(object source, ControlCustomizationEventArgs e)
        {
            if (e.FieldName == "SE")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleRight;

            }
                
            if (e.FieldName == "NSRSBH")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleLeft;

            }
            if (e.FieldName == "NSRMC")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleLeft;

            }
        }
        public string GetWhereString()
        {
            //绑定值
            var taxClass = IsNull(ComboBoxExtension.GetValue<string>("TaxClass"),Request["TaxClass"]);
            var yskm = IsNull(ComboBoxExtension.GetValue<string>("Yskm"), Request["Yskm"]);
            var hydl = IsNull(ComboBoxExtension.GetValue<string>("Hydl"), Request["Hydl"]);
            var zsfs = IsNull(ComboBoxExtension.GetValue<string>("Zsfs"), Request["Zsfs"]);
            var sksx = IsNull(ComboBoxExtension.GetValue<string>("Sksx"), Request["Sksx"]);
            var sjly = IsNull(ComboBoxExtension.GetValue<string>("Sjly"), Request["Sjly"]);
            var nsrsbh = Request["nsrsbh"];
            var nsrbm = Request["nsrbm"];
            var nsrmc = Request["nsrmc"];
            var rKRQBeginDate = Request["RKRQBeginDate"];
            var rKRQEndDate = Request["RKRQEndDate"];
            var sSRQBeginDate = Request["SSRQBeginDate"];
            var sSRQEndDate = Request["SSRQEndDate"];
            var isReject = Request["isReject"] == "C";
            var SKSJA = Request["SKSJA"];
            var SKSJB = Request["SKSJB"];

            ViewData["TaxClass"] = taxClass;
            ViewData["Yskm"] = yskm;
            ViewData["Hydl"] = hydl;
            ViewData["Zsfs"] = zsfs;
            ViewData["Sksx"] = sksx;
            ViewData["Sjly"] = sjly;
            ViewData["nsrsbh"] = nsrsbh;
            ViewData["nsrbm"] = nsrbm;
            ViewData["nsrmc"] = nsrmc;
            ViewData["RKRQBeginDate"] = rKRQBeginDate;
            ViewData["RKRQEndDate"] = rKRQEndDate;
            ViewData["SSRQBeginDate"] = sSRQBeginDate;
            ViewData["SSRQEndDate"] = sSRQEndDate;
            ViewData["IsReject"] = isReject;

            var filter = "";
            if (!string.IsNullOrEmpty(nsrsbh)) filter = string.Format("nsrsbh = '{0}'", nsrsbh);
            else if (!string.IsNullOrEmpty(nsrbm)) filter = string.Format("nsrbm like '%{0}%'", nsrbm);
            else if (!string.IsNullOrEmpty(nsrmc)) filter = string.Format("nsrmc like '%{0}%'", nsrmc);
            else
                filter = "1=1 ";

            if (!string.IsNullOrEmpty(taxClass))
            {
                filter += string.Format(" and ZSXM_DM = '{0}' ", taxClass);
            }
            if (!string.IsNullOrEmpty(yskm))
            {
                filter += string.Format(" and yskm_DM = '{0}' ", yskm);
            }
            if (!string.IsNullOrEmpty(hydl))
            {
                filter += string.Format(" and V_SB_ZSXX.HYDL_DM = '{0}' ", hydl);
            }
            if (!string.IsNullOrEmpty(zsfs))
            {
                filter += string.Format(" and zsfs_DM = '{0}' ", zsfs);
            }
            if (!string.IsNullOrEmpty(sksx))
            {
                filter += string.Format(" and sksx_DM = '{0}' ", sksx);
            }
            if (!string.IsNullOrEmpty(sjly))
            {
                filter += string.Format(" and FDataSource {0} 'GS' ", sjly == "1" ? "=" : "<>");
            }
            if (!string.IsNullOrEmpty(rKRQBeginDate) || !string.IsNullOrEmpty(rKRQEndDate))
            {
                var begin = string.IsNullOrEmpty(rKRQBeginDate) ? DateTime.MinValue.ToString() : rKRQBeginDate;
                var end = string.IsNullOrEmpty(rKRQEndDate) ? DateTime.MaxValue.ToString() : rKRQEndDate;
                filter += string.Format(" and rKRQ >= '{0}' AND rKRQ <= '{1}'", begin, end);
            }
            if (!string.IsNullOrEmpty(sSRQBeginDate) || !string.IsNullOrEmpty(sSRQEndDate))
            {
                var begin = string.IsNullOrEmpty(sSRQBeginDate) ? DateTime.MinValue.ToString() : sSRQBeginDate;
                var end = string.IsNullOrEmpty(sSRQEndDate) ? DateTime.MaxValue.ToString() : sSRQEndDate;
                filter += string.Format(" and sssq_q >= '{0}' AND sssq_z <= '{1}'", begin, end);
            }
            if (isReject)
            {
                //var beginDate = string.IsNullOrEmpty(rKRQBeginDate) ? DateTime.MinValue : DateTime.Parse(rKRQBeginDate);
                //var endDate = string.IsNullOrEmpty(rKRQEndDate) ? DateTime.MaxValue : DateTime.Parse(rKRQEndDate);
                //var rejectTaxSql = new BLL.VSBZSXX().GetRejectTaxSql( beginDate,endDate );
                BLL.Common CommonBLL = new BLL.Common();
                string year = (decimal.Parse(OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR))).ToString();
                string str = CommonBLL.GetGetRejectTaxSqlByYear(year);
                string strwhere1 = "";
                if (str != "")
                {
                    strwhere1 = @"   NOT EXISTS (SELECT  ZSXH
         FROM fund.V_SB_ZSXX s WHERE (" + str + @")  AND
                                   [fund].[V_SB_ZSXX].FDataSource = s.FDataSource AND
                                   [fund].[V_SB_ZSXX].ZSXH = s.ZSXH ) ";
                }
                filter += string.Format(" and  {0}", strwhere1);
            }
            if (!string.IsNullOrEmpty(SKSJA))
            {
                filter += string.Format(" and SE > '{0}'", SKSJA);
            }
            if (!string.IsNullOrEmpty(SKSJB))
            {
                filter += string.Format(" and SE < '{0}'", SKSJB);
            }
            return filter;

        }

        public QueryTaxController()
        {
            //绑定列表
            var taxClasses = new EnterpriseFund.BLL.TaxClass().GetModelList("");
            taxClasses.Insert(0, new Model.TaxClass());

            var hydls = new EnterpriseFund.BLL.DM_HYDL().GetModelList("") ;
            hydls.Insert(0, new Model.DM_HYDL());

            var zsfses = new EnterpriseFund.BLL.DM_ZSFS().GetModelList("");
            zsfses.Insert(0, new Model.DM_ZSFS());

            var sksxes = new EnterpriseFund.BLL.DM_SKSX().GetModelList("");
            sksxes.Insert(0, new Model.DM_SKSX());

            var yskms = new List<Model.DM_YSKM>();
            var taxClass = ComboBoxExtension.GetValue<string>("TaxClass");
            if (!string.IsNullOrEmpty(taxClass))
            {
                yskms = new EnterpriseFund.BLL.DM_YSKM().GetModelList("ZSXM_DM = '" + taxClass + "'");
                yskms.Insert(0, new Model.DM_YSKM());
            }
            else
            {
                yskms = new EnterpriseFund.BLL.DM_YSKM().GetModelList("");
                yskms.Insert(0, new Model.DM_YSKM());
            }

            ViewBag.TaxClasses = taxClasses;
            ViewBag.Yskms = yskms;
            ViewBag.Hydls = hydls;
            ViewBag.Zsfses = zsfses;
            ViewBag.Sksxes = sksxes;
        }

        public System.Data.DataTable GetVSBZSXX()
        { 
            var strWhere = GetWhereString();
            var zsxx = new BLL.VSBZSXX().QueryTax(strWhere).AsEnumerable();
            foreach (var r in zsxx)
            {
                r["RKRQ"] = string.IsNullOrEmpty(r["RKRQ"].ToString()) ? "" : DateTime.Parse(r["RKRQ"].ToString()).ToString("yyyy-MM-dd");
            }
            DataTable dt = new DataTable();
            if (dt.Columns.Count==0)
            {
                dt.Columns.Add("FDataSource");
                dt.Columns.Add("ZSXH");
                dt.Columns.Add("NSRDZDAH");
                dt.Columns.Add("NSRSBH");
                dt.Columns.Add("NSRBM");
                dt.Columns.Add("NSRMC");
                dt.Columns.Add("SSSQ_Q");
                dt.Columns.Add("SSSQ_Z");
                dt.Columns.Add("ZSXM_DM");
                dt.Columns.Add("ZSXM_MC");
                dt.Columns.Add("ZSPM_DM");
                dt.Columns.Add("ZSPM_MC");
                dt.Columns.Add("SKZL_DM");
                dt.Columns.Add("SKZL_MC");
                dt.Columns.Add("SKSX_DM");
                dt.Columns.Add("SKSX_MC");
                dt.Columns.Add("SE",typeof(decimal));
                dt.Columns.Add("RKRQ");
                dt.Columns.Add("HYDL_DM");
                dt.Columns.Add("HYDL_MC");
                dt.Columns.Add("ZSFS_DM");
                dt.Columns.Add("ZSFS_MC");
                dt.Columns.Add("YSKM_DM");
                dt.Columns.Add("YSKM_MC");
            }
            foreach ( DataRow r in zsxx)
            { 
                DataRow dr = dt.NewRow();
                foreach (DataColumn dc in dt.Columns)
                {
                    if (dc.ColumnName == "RKRQ")
                    {
                        dr["RKRQ"] = string.IsNullOrEmpty(r["RKRQ"].ToString()) ? "" : DateTime.Parse(r["RKRQ"].ToString()).ToString("yyyy-MM-dd");
                    }
                    else if (dc.ColumnName == "SE")
                   {
                       dr["SE"] = decimal.Parse(r["SE"].ToString());
                   }
                    else
                    { 
                        dr[dc.ColumnName] = r[dc.ColumnName];
                    }
                   
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public string GetYskms(string TaxClass)
        {
            var yskms = new List<Model.DM_YSKM>();
            if (!string.IsNullOrEmpty(TaxClass))
            {
                yskms = new EnterpriseFund.BLL.DM_YSKM().GetModelList("ZSXM_DM = '" + TaxClass + "'");
                yskms.Insert(0, new Model.DM_YSKM());
            }
            else
            {
                 yskms = new EnterpriseFund.BLL.DM_YSKM().GetModelList("");
                yskms.Insert(0, new Model.DM_YSKM());
            }
            //var yskms = new EnterpriseFund.BLL.DM_YSKM().GetModelList("ZSXM_DM = '" + TaxClass + "'");
           // yskms.Insert(0, new Model.DM_YSKM());
            return JsonConvert.SerializeObject(yskms);
        }

        [HttpPost]
        public ActionResult Index(string id)
        {
           // var vsbzsxx = GetVSBZSXX();
           // return View(vsbzsxx);
            return View();
        }

        [HttpGet]
        [AuthorityActionFilter("m_QueryTax", Order = 1)]
        [LogPageActionFilter("税款查询", Order = 2)]
        public ActionResult Index()
        {
          //  GetWhereString();
            return View();
        }

        public ActionResult QueryTaxPartial()
        {
            var vsbzsxx = GetVSBZSXX();
            return View(vsbzsxx);
        }



        #region 导出EXCEL

        public ActionResult ExportToXls()
        {
            var table = GetVSBZSXX();
            return GridViewExtension.ExportToXls(ExportGridViewSettings, table, HttpUtility.UrlEncode("税款查询导出.xls"), true);
        }


        static GridViewSettings exportGridViewSettings; 
        public static GridViewSettings ExportGridViewSettings
        {
            get
            {
                if (exportGridViewSettings == null)
                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }

        public static GridViewSettings CreateExportGridViewSettings()
        {
            var setting = new GridViewSettings();

            setting.Name = "gvEditing";
            setting.KeyFieldName = "ZSXH";
            setting.CallbackRouteValues = new { Controller = "QueryTax", Action = "QueryTaxPartial" };
            setting.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            setting.SettingsPager.PageSize = EnterpriseFund.Common.GlobalConstant.CONSTRING_PAGESIZE;

            setting.Columns.Add("NSRSBH", "纳税人识别号"); 
            setting.Columns.Add("NSRBM", "纳税人编码");
            setting.Columns.Add("NSRMC", "纳税人名称");
            setting.Columns.Add("RKRQ", "入库日期");
            setting.Columns.Add("ZSXM_MC", "征收项目");
            setting.Columns.Add("YSKM_MC", "预算科目");
            setting.Columns.Add("SE", "税额").PropertiesEdit.DisplayFormatString = "c"; 
            setting.Columns.Add("HYDL_MC", "行业类别");
            setting.Columns.Add("SKZL_MC", "税款种类");
            setting.Columns.Add("SKSX_MC", "税款属性");
            setting.Columns.Add("ZSFS_MC", "征收方式");
            setting.Columns.Add("FDataSource", "国地税标识");
            setting.SettingsExport.Styles.Header.BackColor = System.Drawing.Color.White;
            setting.SettingsExport.Styles.Header.ForeColor = System.Drawing.Color.Black;
            setting.SettingsLoadingPanel.Text = "数据读取中...";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRSBH").DisplayFormat = "总计:";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "SE").DisplayFormat = "￥{0}";
            setting.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "SE").DisplayFormat = "合计:￥{0}";
            setting.Settings.ShowGroupPanel = true;
            setting.Settings.ShowFooter = true;

            setting.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
            setting.ClientSideEvents.EndCallback = "function(){}";

            setting.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }
            };
            setting.SettingsBehavior.EnableCustomizationWindow = true;
			
			
            setting.PreRender = setting.BeforeGetCallbackResult = (sender, e) =>
            {


                MVCxGridView gridView = sender as MVCxGridView;
                MVCxGridViewState gridViewState = new MVCxGridViewState(gridView);
                OperateSession.SetToCache(gridViewState, "QueryTax");


            };
            return setting;
        }

        #endregion
    }
}
